import * as user from '@/api/user'
import * as common from '@/common/common'
const state = {

  // 用户是否已经登陆
  isLogin: localStorage.getItem('userInfo') || false,
  // 用户信息
  userDetail: ''

}

const mutations = {
  // 保存token在state中
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ISLOGIN: (state, isLogin) => {
    state.isLogin = isLogin
  },

  // 保存用户名
  SET_NAME: (state, name) => {
    state.name = name
  },
  // 保存用户信息
  SET_USERDETAIL: (state, userDetail) => {
    state.userDetail = userDetail
  }

}

const actions = {

  // 用户登陆
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      user.login({ username: username.trim(), password: password }).then(res => {
        // 登陆成功，保存token在localStorage
        common.setItemToStorage('userInfo', res.object)
        commit('SET_ISLOGIN', true)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  userRegister({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      user.register({ username: username.trim(), password: password }).then(res => {
        common.setItemToStorage('token', res.object)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户登陆之后获取用户信息
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      user.getInfo().then(res => {
        commit('SET_USERDETAIL', res.object)
        commit('SET_ISLOGIN', true)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出登陆
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      common.userMessageInit()
      resolve()
    })
  },

  update({ commit, state }, userQo) {
    return new Promise((resolve, reject) => {
      user.update(userQo).then(res => {
        // 更改密码成功，退出重新登陆
        resolve(res)
      }).catch((error) => {
        reject(error)
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
